package com.example.myapplication.ui.activity.login

import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.ui.vm.SharedViewModel
import com.kun.base.env.Constants
import com.kun.base.ui.AbsBaseActivity
import com.kun.base.util.MMKVUtils
import com.kun.base.util.ToastUtils
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.toolbar_layout.*

/**
 *登录页面
 *
 * @author : Kun
 * @date : 2021/6/4
 * @time : 9:56
 */
@Route(path = ARouterPath.LOGIN)
class LoginActivity : AbsBaseActivity() {
    private lateinit var loginViewModel: LoginViewModel
    private lateinit var sharedViewModel: SharedViewModel

    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun initViewModel() {
        loginViewModel = getActivityScopeViewModel(LoginViewModel::class.java)
        sharedViewModel = getApplicationScopeViewModel(SharedViewModel::class.java)

        loginViewModel.loginRequest.loginResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                ToastUtils.showShortToast("登录成功")
                MMKVUtils.put(Constants.USERNAME_CACHE_KEY, t.data!!.username)
                sharedViewModel.userdata.value = t.data
                finish()
            } else {
                ToastUtils.showShortToast(t.errorMsg.toString())
            }
        })
    }

    override fun initView() {
        iv_back.setOnClickListener { finish() }
        tv_title.text = getString(R.string.login)

        tv_right.visibility = View.VISIBLE
        tv_right.text = getString(R.string.register)
        tv_right.textSize = 12f
        tv_right.setOnClickListener {
            ARouter.getInstance().build(ARouterPath.REGISTER).navigation()
        }

        tv_login.setOnClickListener {
            login()
        }
        if (sharedViewModel.userdata.value != null) {
            sharedViewModel.userdata.value = null
        }

    }

    fun login() {
        val userName = et_account.text.toString()
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.showShortToast("请输入用户名")
            return
        }
        val password = et_password.text.toString()
        if (TextUtils.isEmpty(password)) {
            ToastUtils.showShortToast("请输入密码")
            return
        }
        loginViewModel.requestLogin(userName, password)
    }
}